using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using ThridGroup.ERP.Application.WarehouseManagement;
using ThridGroup.ERP.WarehouseManagement;
using ThridGroup.ERP.DTO;

namespace ThridGroup.ERP.Web.Areas.WarehouseManagement.Controllers
{
    [Area("WarehouseManagement")]
    [Route("WarehouseManagement/[controller]")]
    public class CodingmanagementController : AbpController
    {
        private readonly ICodingmanagementService _codingmanagementService;
        private readonly ILogger<CodingmanagementController> _logger;

        public CodingmanagementController(
            ICodingmanagementService codingmanagementService,
            ILogger<CodingmanagementController> logger)
        {
            _codingmanagementService = codingmanagementService;
            _logger = logger;
        }

        /// <summary>
        /// 赋码管理首页
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("")]
        [Route("Index")]
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取赋码管理列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetCodingmanagements")]
        public async Task<IActionResult> GetCodingmanagements(string barTypes = null, string businessCode = null, string businessName = null, int page = 1, int limit = 10)
        {
            try
            {
                _logger.LogInformation($"接收到获取赋码管理列表请求：barTypes={barTypes}, businessCode={businessCode}, businessName={businessName}, page={page}, limit={limit}");
                
                List<CodingmanagementDto> allData;
                try
                {
                    // 按条件查询
                    if (!string.IsNullOrEmpty(barTypes) || !string.IsNullOrEmpty(businessCode) || !string.IsNullOrEmpty(businessName))
                    {
                        // 修改调用方式，确保传递正确的参数
                        allData = await _codingmanagementService.GetCodingmanagementsByCondition(barTypes, businessCode, businessName);
                        
                        // 不需要重复过滤，因为已经在服务层处理了
                        _logger.LogInformation($"条件查询结果数：{allData?.Count ?? 0}条");
                    }
                    else
                    {
                        allData = await _codingmanagementService.GetCodingmanagements();
                        _logger.LogInformation($"获取全部数据结果数：{allData?.Count ?? 0}条");
                    }
                }
                catch (Exception serviceEx)
                {
                    _logger.LogError(serviceEx, $"服务层获取赋码管理数据失败：{serviceEx.Message}");
                    return Json(new { code = 1, msg = "获取数据失败：" + serviceEx.Message, count = 0, data = new List<CodingmanagementDto>() });
                }
                
                // 检查是否有数据
                if (allData == null)
                {
                    _logger.LogWarning("获取赋码管理列表成功，但数据为null");
                    return Json(new { code = 0, msg = "获取成功，但无数据", count = 0, data = new List<CodingmanagementDto>() });
                }
                
                if (!allData.Any())
                {
                    _logger.LogInformation("获取赋码管理列表成功，但无记录");
                    return Json(new { code = 0, msg = "获取成功，但无数据", count = 0, data = new List<CodingmanagementDto>() });
                }

                // 计算分页数据
                var totalCount = allData.Count;
                var pageData = allData
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .ToList();

                _logger.LogInformation($"获取赋码管理列表成功，总数：{totalCount}，当前页数据量：{pageData.Count}");
                return Json(new { code = 0, msg = "获取成功", count = totalCount, data = pageData });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取赋码管理列表失败：{ex.Message}，堆栈：{ex.StackTrace}");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message, count = 0, data = new List<CodingmanagementDto>() });
            }
        }

        /// <summary>
        /// 获取单个赋码管理
        /// </summary>
        /// <param name="id">赋码管理ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetById/{id}")]
        public async Task<IActionResult> GetCodingmanagement(int id)
        {
            try
            {
                _logger.LogInformation($"接收到获取单个赋码管理请求，ID：{id}");

                if (id <= 0)
                {
                    return Json(new { code = 1, msg = "无效的赋码管理ID", data = new object() });
                }

                var model = await _codingmanagementService.GetCodingmanagement(id);
                if (model == null)
                {
                    return Json(new { code = 1, msg = $"未找到ID为{id}的赋码管理", data = new object() });
                }

                return Json(new { code = 0, msg = "获取成功", data = model });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取单个赋码管理失败，ID：{id}，错误：{ex.Message}");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message, data = new object() });
            }
        }

        /// <summary>
        /// 添加赋码管理
        /// </summary>
        /// <param name="input">赋码管理数据</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Add")]
        public async Task<IActionResult> Add([FromBody] CreateUpdateCodingmanagementDto input)
        {
            try
            {
                _logger.LogInformation($"接收到添加赋码管理请求：BarCode={input?.BarCode}, BusinessCode={input?.BusinessCode}");

                if (input == null)
                {
                    return Json(new { code = 1, msg = "无效的赋码管理数据" });
                }

                var id = await _codingmanagementService.AddCodingmanagement(input);
                return Json(new { code = 0, msg = "添加成功", id = id });
            }
            catch (ArgumentException argEx)
            {
                _logger.LogWarning(argEx, $"添加赋码管理参数验证失败：{argEx.Message}");
                return Json(new { code = 1, msg = argEx.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加赋码管理失败：{ex.Message}");
                return Json(new { code = 1, msg = "添加失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 更新赋码管理
        /// </summary>
        /// <param name="input">赋码管理数据</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Update")]
        public async Task<IActionResult> Update([FromBody] CodingmanagementDto input)
        {
            try
            {
                _logger.LogInformation($"接收到更新赋码管理请求：ID={input?.Id}, BarCode={input?.BarCode}, BusinessCode={input?.BusinessCode}");

                if (input == null || input.Id <= 0)
                {
                    return Json(new { code = 1, msg = "无效的赋码管理数据" });
                }

                var updateDto = new CreateUpdateCodingmanagementDto
                {
                    BarCode = input.BarCode,
                    BarFormat = input.BarFormat,
                    BarTypes = input.BarTypes,
                    BarContext = input.BarContext,
                    BusinessCode = input.BusinessCode,
                    BusinessName = input.BusinessName,
                    IsNo = input.IsNo
                };

                var id = await _codingmanagementService.UpdateCodingmanagement(input.Id, updateDto);
                return Json(new { code = 0, msg = "更新成功", id = id });
            }
            catch (ArgumentException argEx)
            {
                _logger.LogWarning(argEx, $"更新赋码管理参数验证失败：{argEx.Message}");
                return Json(new { code = 1, msg = argEx.Message });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新赋码管理失败：{ex.Message}");
                return Json(new { code = 1, msg = "更新失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 删除赋码管理
        /// </summary>
        /// <param name="id">赋码管理ID</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Delete/{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                _logger.LogInformation($"接收到删除赋码管理请求，ID：{id}");

                if (id <= 0)
                {
                    return Json(new { code = 1, msg = "无效的赋码管理ID" });
                }

                await _codingmanagementService.DeleteCodingmanagement(id);
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除赋码管理失败，ID：{id}，错误：{ex.Message}");
                return Json(new { code = 1, msg = "删除失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 检查条码是否存在
        /// </summary>
        /// <param name="barCode">条码</param>
        /// <param name="id">排除的ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("CheckBarCode")]
        public async Task<IActionResult> CheckBarCode(string barCode, int? id = null)
        {
            try
            {
                if (string.IsNullOrEmpty(barCode))
                {
                    return Json(new { code = 0, msg = "条码不能为空", exists = false });
                }

                var exists = await _codingmanagementService.IsBarCodeExist(barCode, id);
                return Json(new { code = 0, msg = "检查成功", exists = exists });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"检查条码失败：{ex.Message}");
                return Json(new { code = 1, msg = "检查失败：" + ex.Message, exists = false });
            }
        }

        /// <summary>
        /// 检查业务编码是否存在
        /// </summary>
        /// <param name="businessCode">业务编码</param>
        /// <param name="id">排除的ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("CheckBusinessCode")]
        public async Task<IActionResult> CheckBusinessCode(string businessCode, int? id = null)
        {
            try
            {
                if (string.IsNullOrEmpty(businessCode))
                {
                    return Json(new { code = 0, msg = "业务编码不能为空", exists = false });
                }

                var exists = await _codingmanagementService.IsBusinessCodeExist(businessCode, id);
                return Json(new { code = 0, msg = "检查成功", exists = exists });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"检查业务编码失败：{ex.Message}");
                return Json(new { code = 1, msg = "检查失败：" + ex.Message, exists = false });
            }
        }
    }
} 